"""
DHT爬虫启动入口
~~~~~~~~~~~~

提供系统启动和初始化功能。
"""

import logging
import sys
import asyncio
import signal
from src.core.crawler import Crawler
from src.log.logger import setup_logger

sys.dont_write_bytecode = True


async def shutdown(crawler: Crawler, loop: asyncio.AbstractEventLoop) -> None:
    """优雅关闭爬虫服务"""
    logger = setup_logger('runner.shutdown')
    logger.info("正在关闭爬虫...")
    await crawler.stop_crawler()
    loop.stop()

async def startup() -> None:
    """启动爬虫服务"""
    logger = setup_logger('runner.startup')
    crawler = Crawler()
    
    # 获取当前事件循环
    loop = asyncio.get_running_loop()
    
    def signal_handler():
        """信号处理函数"""
        logger.info("收到终止信号")
        asyncio.create_task(shutdown(crawler, loop))
    
    # 注册信号处理
    for sig in (signal.SIGINT, signal.SIGTERM):
        loop.add_signal_handler(sig, signal_handler)

    try:
        logger.info("正在启动DHT爬虫...")
        # 启动爬虫
        await crawler.start_crawler()
        
    except Exception as e:
        logger.error(f"爬虫运行出错: {e}")
        await shutdown(crawler, loop)

def main() -> None:
    """主函数：程序入口点"""
    logger = setup_logger('runner.main')
    try:
        # 创建新的事件循环
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        
        # 启动爬虫任务
        loop.create_task(startup())
        
        # 运行事件循环
        loop.run_forever()
        
    except KeyboardInterrupt:
        logger.info("程序被用户中断")
    except Exception as e:
        logger.error(f"程序运行错误: {e}", exc_info=True)
        sys.exit(1)
    finally:
        loop.close()

if __name__ == '__main__':
    main() 